<template>
  <page-wrap :showTop="false" back hide-tab bgColor="#F9F9F9" title="定制简历">
    <view class="result-chat">
      <view class="steps">
        <Subsection :list="stepList" :current="current" @change="handleStepChange"></Subsection>
      </view>
      <scroll-view scroll-y class="content" >
        <view v-if="current == 0" class="advantage-wrap">
          <view class="box-wrap">
            <AdvantageBox type="advantage" title="个人强项" :list="advantage"></AdvantageBox>
          </view>
          <view class="box-wrap">
            <AdvantageBox type="disadvantage" title="相对弱势" :list="disadvantage"></AdvantageBox>
          </view>
        </view>
        <view v-if="current == 1" class="comparison-wrap">
          <Comparison :resume="resume" ref="comparison"></Comparison>
        </view>
        <view v-if="current == 2">
          <BaseInfo ref="baseInfo" :info="baseInfo" @submit="handleBaseInfoSubmit"></BaseInfo>
          <view class="evaluate">
            <view class="evaluate-title">自我评价</view>
            <view class="box-content">
              <u-input
                  type="textarea"
                  v-model="grzz"
                  placeholder="请输入自我评价"
                  :clearable="false"
                  class="input-grzz"
                />
            </view>
          </view>
          <Education ref="education" :edus="resume.edus || []" @submit="handleEducationSubmit"></Education>
          <Experience ref="experience" :work="resume.work || []" @submit="handleExperienceSubmit"></Experience>
          <Project ref="project" :project="resume.project || []" @submit="handleProjectSubmit"></Project>
        </view>
      </scroll-view>
      <view class="action">
        <view class="popup" v-if="current == 1 && isShowNextTips">
          <view class="popup-content">点击“下一步”，即可编辑已采纳的内容</view>
          <u-icon name="close-circle" @click="isShowNextTips = false"></u-icon>
        </view>
        <view v-if="current != 0" class="btn-prev">
          <u-button type="primary" plain shape="circle" @click="handlePrev">上一步</u-button>
        </view>
        <view v-if="current != 2" class="btn-next" :class="{'whole': current == 0}">
          <u-button type="primary" shape="circle" @click="handleNext">下一步</u-button>
        </view>
        <view v-if="current == 2"  class="btn-create" >
          <u-button type="primary" shape="circle" @click="handleCreate">生成简历</u-button>
        </view>
      </view>
    </view>
    <u-popup v-model="showAction" mode="bottom" safe-area-inset-bottom :closeable="!actionType" @close="handlePopupClose">
      <view v-if="!actionType" class="create-content">
        <view class="create-tips">请勾选说明，再选择要生成的简历方式：</view>
        <view class="checkbox">
          <u-checkbox v-model="confirmCheck">我已确认简历信息无误</u-checkbox>
        </view>
        <view class="create-list">
          <view class="create-list-item" @click="handleCreateFile">
            生成附件简历
          </view>
          <view class="create-list-item" @click="handleSynchronize">
            同步到在线简历
          </view>
        </view>
      </view>
      <view v-if="actionType == 'file'" class="file-wrap">
        <view class="file-title">附件简历</view>
        <view class="file-content">
          <view v-if="!isCreated">
            <u-loading mode="flower" size="100" class="file-loading"></u-loading>
            <view>附件简历生成中...</view>
          </view>
          <view v-else>
            附件简历已生成：
            <view class="file-item">
              <File :file="fileObj"></File>
            </view>
            <view class="btn-share">
              <u-button type="primary" plain @click="handleShareFile">分享到微信聊天</u-button>
            </view>
          </view>
        </view>
      </view>
      <view v-if="actionType == 'synchronize'" class="synchronize">
        <view class="synchronize-title text-center">简历同步</view>
        <view class="synchronize-text" v-if="!isSynchronized">
          当前内容同步后，将会覆盖在线简历已有的内容，是否确定同步？
        </view>
        <view class="text-center" v-if="isSynchronized">
          <u-icon name="checkmark-circle-fill" size="100"></u-icon>
          <view>
            简历已同步
          </view>
        </view>
        <view v-if="!isSynchronized" class="text-center">
          <view class="btn-cancel">
            <u-button @click="handleSynchronizeCancel">取消</u-button>
          </view>
          <view class="btn-confirm">
            <u-button type="primary" :loading="synchronizeLoading" @click="handleSynchronizeConfirm">确定</u-button>
          </view>
        </view>
      </view>
    </u-popup>
  </page-wrap>
</template>
<script>
import AdvantageBox from './components/AdvantageBox.vue';
import BaseInfo from './components/BaseInfo.vue';
import Education from './components/Education.vue';
import Experience from './components/Experience.vue';
import Project from './components/Project.vue';
import File from './components/File.vue';
import Subsection from './components/Subsection.vue';
import Comparison from './components/Comparison.vue';
import { getTaskProgress, exportCustomizedResume, syncCustomizedResume } from '../api/resumeApi.js';
import { getPersonResumeAttachment } from '@/api/modules/resumeCreate';

export default {
  components: {
    AdvantageBox,
    BaseInfo,
    Education,
    Experience,
    Project,
    File,
    Subsection,
    Comparison,
  },
  data() {
    return {
      taskId: '',
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      current: 0,
      stepList: [
        {
          name: '强弱分析',
        },
        {
          name: '优化对比',
        },
        {
          name: '简历预览',
        }
      ],
      showAction: false,
      confirmCheck: false,
      actionType: '',
      fileUrl: '',
      isCreated: false,
      isSynchronized: false,
      synchronizeLoading: false,
      resume: null,
      originResume: null,
      advantage: [],
      disadvantage: [],
      baseInfo: {},
      editBaseInfo: {},
      grzz: '',
      editResume: {},
      startTime: null,
      timer: null,
      fileObj: '',
      isShowNextTips: true,
      exportTaskId: '',
    }
  },
  onLoad(opt) {
    this.taskId = opt.taskId;
    this.getTaskProgress();
  },
  beforeDestroy() {
    clearTimeout(this.timer);
  },
  methods: {
    getTaskProgress() {
      const params = {
        taskId: this.taskId,
      };
      getTaskProgress(params)
        .then((res) => {
          if (res && res.data) {
            this.resume = res.data.result.resume;
            this.originResume = JSON.parse(JSON.stringify(res.data.result.resume));
            this.baseInfo = {
              iname: this.resume.iname,
              bday: this.resume.bday,
              hkaName: this.resume.hka_name,
              edu: this.resume.edu,
            }
            this.grzz = this.resume.grzz;
            this.advantage = res.data.result.strengthAnalysis.advantage;
            this.disadvantage = res.data.result.strengthAnalysis.disadvantage;
          }
        })
        .catch((err) => {
        });
    },
    handleNext() {
      if (this.current == 1) {
          let comparisionData = this.$refs.comparison.exportData();
          if (comparisionData.grzz) {
            this.resume.grzz = comparisionData.grzz[0].value;
            this.grzz = comparisionData.grzz[0].value;
          }
          if (comparisionData.edus) {
            comparisionData.edus.forEach((item,index) => {
              this.resume.edus[index].edus = item.value;
            });
          }
          if (comparisionData.work) {
            comparisionData.work.forEach((item,index) => {
              this.resume.work[index].workdesc = item.value;
            });
          }
          if (comparisionData.project) {
            comparisionData.project.forEach((item,index) => {
              this.resume.project[index].person_projectDesc = item.value;
            });
          }
          setTimeout(() => {
            this.current++;
          }, 500);
      } else {
        this.current++;
      }
    },
    handlePrev() {
      var that = this;
      if (this.current == 2) {
        uni.showModal({
          title: '提示',
          content: '返回上一步，当前页面的编辑内容将不会保留，请确认是否返回？',
          success: function (res) {
            if (res.confirm) {
              that.resume = JSON.parse(JSON.stringify(that.originResume));
              that.editResume = {};
              that.editBaseInfo = {};
              that.grzz = '';
              that.current--;
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        });
      } else {
        this.current--;
      }
    },
    handleCreate() {
      this.showAction = true;
    },
    createFile() {
      let content = {
        ...this.resume,
        ...this.editResume,
        ...this.editBaseInfo,
        grzz: this.grzz,
        hka_name: this.editBaseInfo.hkaName,
      }
      const params = {
        personId: this.personId,
        resumeContent: JSON.stringify(content),
      };

      exportCustomizedResume(params).then(res => {
        if (res.code == 200) {
          this.startTime = new Date().getTime();
          this.exportTaskId = res.data.id;
          this.getResumeTime();
        }
      })
    },
    getResumeTime() {
      clearTimeout(this.timer); // 清除定时器
      // 超过30分钟则停止轮询
      if (new Date().getTime() - this.startTime > 30 * 1000 * 60) {
        clearTimeout(this.timer);
        uni.showToast({ icon: 'none', title: '服务器繁忙，请稍后重试' });
        return;
      }
      // 3s一次, 轮询中
      this.timer = setTimeout(() => {
        this.getResume(); // 调用轮询
      }, 3000);
    },
    getResume() {
      let param = {
        personId: this.personId,
        id: this.exportTaskId,
      };
      getPersonResumeAttachment(param)
        .then((res) => {
          if (res && res.data.attUrl) {
            clearTimeout(this.timer);
            this.fileUrl = res.data.attUrl;
            this.fileObj = {
              fileName: '附件简历.pdf' || res.data.attName,
              fileSize: '',
            }
            this.isCreated = true;
          } else {
            this.getResumeTime();
          }
        })
        .catch((err) => {
          // 请求错误,也继续轮询
          this.getResumeTime();
        });
    },
    validateAllForms() {
      // 基础信息校验
      let baseInfoValid = this.$refs.baseInfo.validateAll();
      // 教育经历校验
      let eduValid = this.$refs.education.validateAll();
      // 工作经历校验
      let experienceValid = this.$refs.experience.validateAll();
      // 项目经历校验
      let projectValid = this.$refs.project.validateAll();
      if (!baseInfoValid || !eduValid || !experienceValid || !projectValid) {
        uni.showToast({
          title: '请完善所有必填信息',
          icon: 'none',
        });
        return false;
      }
      return true;
    },
    
    handleCreateFile() {
      if (!this.confirmCheck) {
        uni.showToast({
          title: '请确认并勾选说明',
          icon: 'none',
        });
        return;
      };
      this.$refs.baseInfo.exportData();
      this.$refs.education.exportData();
      this.$refs.experience.exportData();
      this.$refs.project.exportData();

      this.actionType = 'file';
      this.createFile();
    },
    handleSynchronize() {
      if (!this.confirmCheck) {
        uni.showToast({
          title: '请确认并勾选说明',
          icon: 'none',
        });
        return;
      }
      
      const isValid = this.validateAllForms();
      if (!isValid) return;
      
      this.actionType = 'synchronize';
    },
    handleSynchronizeCancel() {
      this.showAction = false;
      this.actionType = '';
    },
    handleSynchronizeConfirm() {
      this.synchronizeLoading = true;
      let content = {
        ...this.resume,
        ...this.editResume,
        ...this.editBaseInfo,
        grzz: this.grzz,
        hka_name: this.editBaseInfo.hkaName,
      }
      const params = {
        personId: this.personId,
        resumeContent: JSON.stringify(content),
      };
      syncCustomizedResume(params).then(res => {
        if (res.code == 200) {
          this.isSynchronized = true;
        }
      }).finally(() => {
        this.synchronizeLoading = true;
      });
    },
    handleShareFile() {
      wx.downloadFile({
        url: this.fileUrl, // 下载url
        success (res) {
          // 下载完成后转发
          wx.shareFileMessage({
            filePath: res.tempFilePath,
            success() {},
            fail: console.error,
          })
        },
        fail: console.error,
      })
    },
    handlePopupClose() {
      this.showAction = false;
      this.actionType = '';
      this.isCreated = false;
      this.isSynchronized = false;
    },
    handleBaseInfoSubmit(data) {
      this.editBaseInfo = data;
    },
    handleEducationSubmit(data) {
      this.editResume.edus = data;
    },
    handleExperienceSubmit(data) {
      this.editResume.work = data;
    },
    handleProjectSubmit(data) {
      this.editResume.project = data;
    },
    handleStepChange(data) {
      this.current = data;
    },
  },
}
</script>
<style lang="scss" scoped>
.result-chat {
  padding: 32rpx;
  padding-top: 196rpx;
  height: 1px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  background-image: url($img-base + "resume/bg.png");
  background-size: 100% auto;
  background-repeat: no-repeat;

  .content {
    height: 1px;
    flex-grow: 1;
  }

  .advantage-wrap {
    padding-bottom: 1px;
  }
}

.steps {
  margin: 32rpx auto;
}

.box-wrap {
  margin-top: 32rpx;
}

.comparison-wrap {
  padding-bottom: 80rpx;
}

.action {
  // position: fixed;
  position: relative;
  left: 0;
  bottom: 0;
  width: 100%;
  padding-top: 32rpx;
  background-color: #F7F8FA;
  z-index: 99;

  .popup {
    position: absolute;
    top: -80rpx;
    right: 0;
    background-color: #fff;
    color: #333;
    border-radius: 25px;
    padding: 10px 20px;
    z-index: 1;
    border: 1rpx solid #CCCCCC;

    &::after {
      content: '';
      position: absolute;
      bottom: -8px;
      left: 60%;
      transform: translateX(-50%);
      width: 0;
      height: 0;
      border-left: 10px solid transparent;
      border-right: 10px solid transparent;
      border-top: 10px solid #fff;
      border-bottom: 0;
    }


    .popup-content {
      display: inline-block;
      margin-right: 32rpx;
      font-size: 24rpx;
    }
  }
}

.btn-next {
  display: inline-block;
  width: 440rpx;

  &.whole {
    display: block;
    margin: 0 auto;
    width: 674rpx;
  }
}

.box-content {
  padding: 24rpx;
  border-radius: 10rpx;
  background-color: #ffffff;
}

.btn-prev {
  display: inline-block;
  margin-right: 12rpx;
  width: 234rpx;
}

.btn-create {
  display: inline-block;
  width: 434rpx;
}

.btn-cancel {
  display: inline-block;
  margin-right: 24rpx;
  vertical-align: middle;
}

.btn-confirm {
  display: inline-block;
  vertical-align: middle;
}

.create-content {
  padding: 12rpx 24rpx;

  .create-tips {
    margin-top: 32rpx;
  }

  .checkbox {
    margin: 32rpx 0;
  }

  .create-list {
    text-align: center;

    &-item {
      padding: 24rpx 0;
    }

    &-item:first-of-type {
      border-bottom: 2rpx solid #eeeeee;
    }
  }
}

.file-wrap {
  .file-title {
    margin: 32rpx 0;
    text-align: center;
  }

  .file-content {
    padding-bottom: 32rpx;
    text-align: center;
  }

  .file-item {
    margin: 64rpx auto;
    width: 300px;
    border: 2rpx solid #eeeeee;
    border-radius: 12rpx;
    box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(0,0,0,0.05);
  }

  .file-loading {
    display: block;
    margin: 64rpx 0 32rpx 0;
  }

  .btn-share {
    margin: 0 auto;
    width: 600rpx;
  }
}

.text-center {
  text-align: center;
}


.evaluate {
  margin-top: 24rpx;
  padding: 24rpx 20rpx;
  border-radius: 30rpx;
  background-color: #ffffff;
  box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(0,0,0,0.05);

  &-title {
    margin: 26rpx 0 46rpx 0;
    font-size: 36rpx;
  }

  .box-content {
    padding: 24rpx;
    border-radius: 20rpx;
    border: 1rpx solid #E5E5E5;
  }

  .input-grzz {
    font-size: 26rpx;
    color: #555555;
  }
}

.synchronize-title {
  margin: 32rpx 0;
}

.synchronize-text {
  margin: 84rpx 64rpx;
}
</style>